package com.example.sxy_project;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;


public class ChatActivity extends AppCompatActivity {
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private List<Msg> msgList = new ArrayList<>();
    private EditText inputText;
    private Button send;
    private RecyclerView msgRecyclerView;
    private MsgAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        //设置返回按钮
        Button back = findViewById(R.id.weixin_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //聊天功能
        inintMsgs();
        inputText = findViewById(R.id.input_txt);
        send = (Button) findViewById(R.id.btn_send);
        msgRecyclerView = (RecyclerView) findViewById(R.id.msg_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        msgRecyclerView.setLayoutManager(layoutManager);
        adapter = new MsgAdapter(msgList);
        msgRecyclerView.setAdapter(adapter);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = inputText.getText().toString();
                if (!"".equals(content)){
                    Msg msg = new Msg(content,Msg.TYPE_SENT);
                    msgList.add(msg);
                    adapter.notifyItemInserted(msgList.size() - 1);
                    msgRecyclerView.scrollToPosition(msgList.size() - 1);
                    inputText.setText("");
                    recrive();
                }else {
                    Toast.makeText(ChatActivity.this,"请输入", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void inintMsgs() {
        Msg msg1 = new Msg("Hello",Msg.TYPE_RECEIVED);
        msgList.add(msg1);
        Msg msg2 = new Msg("Never Mind the Slander and Lies",Msg.TYPE_SENT);
        msgList.add(msg2);
        Msg msg3 = new Msg("long may the sunshine!",Msg.TYPE_RECEIVED);
        msgList.add(msg3);
    }
    private void recrive(){
        Msg msg1 = new Msg("you are dragon,more dragon than me",Msg.TYPE_RECEIVED);
        msgList.add(msg1);
    }
}
